﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UofCASE.AgileProductLinerDSL.Nant.Tasks.visualizing
{
    class XmlElement : IElement
    {
        IDictionary<String, String> attributes;
        String name;
        IList<IElement> children;

        public XmlElement(String name, params String[] numbers)
        {
            this.name = name;
            attributes = new Dictionary<String, String>();
            children = new List<IElement>();
            for (int i = 0; i < numbers.Length; i += 2)
            {
                attributes.Add(numbers[i], numbers[i + 1]);
            }
        }

        public void AddChildElement(IElement child)
        {
            children.Add(child);
        }

        public String render()
        {
            StringBuilder buf = new StringBuilder();
            
            buf.Append("<").Append(name);
            foreach (KeyValuePair<String, String> key in attributes)
            {
                buf.Append(" ").Append(key.Key).Append("=\"").Append(key.Value).Append("\"");
            }

            if (children.Count == 0)
            {
                buf.Append(" />\n");
            }
            else
            {
                buf.Append(">\n");
                foreach (IElement child in children) buf.Append(child.render());
                buf.Append("</").Append(name).Append(">\n");
            }
            return buf.ToString();
        }

        public override string ToString()
        {
            return render();
        }
    }
}
